package bdcin.servlet.actions.mineracao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bdcin.classesbasicas.Documento;
import bdcin.fachada.BDCInFactory;
import bdcin.fachada.IBDCIn;
import bdcin.servlet.actions.Action;
import bdcin.util.Constants;

public class BaixarDocumentoAction extends Action{


	public void executar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//MINERACAO

		IBDCIn facade = BDCInFactory.getFacade();					

		String id = request.getParameter("documento");		
		Documento documento=null;
		try {
			documento = facade.buscarDocumento(Long.valueOf(id));

		} catch (Exception e) {
			request.setAttribute("mensagem", e.getMessage());
			request.getRequestDispatcher("mensagem.jsp").forward(request, response);
		}		

		String nome = documento.getExtensaoArquivo();		
		String extensao = nome.substring(nome.lastIndexOf(".")+1);		

		File f = new File(Constants.localRes);
		if(!f.exists()){
			f.mkdir();
		}
		String caminho = this.criarArquivo(Constants.localRes, documento.getArquivo(),extensao);				

		String nomeArquivo = caminho.substring(caminho.lastIndexOf("/")+1);

		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Disposition", "attachment; filename=" + nomeArquivo);

		InputStream is = null;
		OutputStream out2 = null;
		try {
			out2 = response.getOutputStream();
			is = new FileInputStream(caminho);		    
			int i;
			while ((i=is.read()) != -1) {
				out2.write(i);
			}
		} finally {
			if(out2 != null) {
				out2.flush();
				out2.close();
			}
			if (is != null) {
				is.close();
			}
		}

		//request.setAttribute("caminho",caminho);		
		//request.getRequestDispatcher("mineracao/visualizarDocumentoMineracao.jsp").forward(request, response);


	}

	private String criarArquivo(String local,byte[] data,String extensao){
		String caminho = "";
		try{

			File file = new File(local);

			if(!file.exists()){
				file.mkdir();	
			}			
			String nome = "/resultado."+extensao;
			caminho = local+nome;		
			FileOutputStream output = new FileOutputStream(new File(caminho));
			output.write(data,0,data.length);
			output.flush();
			output.close();

		}catch(Exception e){
			e.printStackTrace();
		}
		return caminho;	
	}


}
